package com.mirama.framework.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
@Slf4j
public class RabbitUtils {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 向Rabbitmq队列发送消息
     *
     * @param queue 队列名称
     * @param msg   消息
     */
    public void sendMsg(String queue, Object msg) {

        String uuid = UUID.randomUUID().toString();

        Map<String, Object> msgMap = new HashMap<>();
        msgMap.put("createTime", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MS_PATTERN));
        msgMap.put("uuid", uuid);
        msgMap.put("msg", msg);

        Message<Map<String, Object>> message = MessageBuilder
                .withPayload(msgMap)
                .setHeader(MessageHeaders.CONTENT_TYPE, MessageProperties.CONTENT_TYPE_JSON)
                .build();

        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(uuid);
        this.rabbitTemplate.convertAndSend(queue, message, correlationData);
    }
}
